package cn.com.gas.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasAnalyseRatioRingEntity;
import cn.com.gas.entity.GasAnalyseRatioWithEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasAnalyseRatioWithService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;



/**
 * 月销同比分析
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-04-15 20:42:03
 */
@Controller
@RequestMapping("/gas/analyse/ratiowith")
public class GasAnalyseRatioWithController {
    @Autowired
    private GasAnalyseRatioWithService gasAnalyseRatioWithService;
    @Autowired
	private GasStationinfoService gasStationinfoService;
    @Autowired
	private HttpSessionService httpSessionService;
    @Autowired
	private DeptService deptService;
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
	@ApiOperation(value = "查询分页数据")
    @PostMapping("/list")
    // @RequiresPermissions("gasAnalyseRatioWith:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody GasAnalyseRatioWithEntity gasAnalyseRatioWith){
    	
    	String currentDeptId = httpSessionService.getCurrentDeptId();
    	
    	List<String> stationIdList = new ArrayList<>();
		LambdaQueryWrapper<GasStationinfoEntity> stationinfoQueryWrapper = Wrappers.lambdaQuery();
		// TODO
		// stationinfoQueryWrapper.eq(GasStationinfoEntity::getPid, "5c8baa4b-081f-41aa-a549-2235b786c7c7");
		// stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
		// stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
		
		if(Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 县区局
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
		} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 市局 
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getType, "group");
			stationinfoQueryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			stationinfoQueryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0,5));
		}else{
			// 省局
		}
		
		List<GasStationinfoEntity> stationinfoList = gasStationinfoService.list(stationinfoQueryWrapper);
		
		for (GasStationinfoEntity gasStationinfoEntity : stationinfoList) {
			stationIdList.add(gasStationinfoEntity.getId());
			
		}
    	
    	Page page = new Page(gasAnalyseRatioWith.getPage(), gasAnalyseRatioWith.getLimit());
        LambdaQueryWrapper<GasAnalyseRatioWithEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        if(TsBqUtils.isNotNull(gasAnalyseRatioWith.getStationName())){
			queryWrapper.like(GasAnalyseRatioWithEntity::getStationName,gasAnalyseRatioWith.getStationName());
		}
		
		if(TsBqUtils.isNotNull(gasAnalyseRatioWith.getYearMonths())){
			queryWrapper.eq(GasAnalyseRatioWithEntity::getYearMonths,gasAnalyseRatioWith.getYearMonths());
		}
		queryWrapper.in(GasAnalyseRatioWithEntity::getStationId,stationIdList);

        IPage<GasAnalyseRatioWithEntity> iPage = gasAnalyseRatioWithService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }
    
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据（税务机关）")
	@PostMapping("/list1")
	@ResponseBody
	public DataResult list1(@RequestBody GasAnalyseRatioRingEntity gasAnalyseRatioRing) {
    	String yearMonths = gasAnalyseRatioRing.getYearMonths();
		if(TsBqUtils.isNull(yearMonths)){
			return DataResult.fail("月份不能为空！");
		}
		
    	String currentDeptId = httpSessionService.getCurrentDeptId();
		
		Page page = new Page(gasAnalyseRatioRing.getPage(), gasAnalyseRatioRing.getLimit());
		LambdaQueryWrapper<SysDept> deptQueryWrapper = Wrappers.lambdaQuery();
		if(Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 县区局
			deptQueryWrapper.eq(SysDept::getId, currentDeptId);
		} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			deptQueryWrapper.like(SysDept::getId, currentDeptId.substring(0,5));
		}
		
		IPage<SysDept> iPage = deptService.page(page, deptQueryWrapper);
		List<SysDept> records = iPage.getRecords();
		for (SysDept dept : records) {
			String deptId = dept.getId();
			
			LambdaQueryWrapper<GasAnalyseRatioWithEntity> analyseRatioWrapper = Wrappers.lambdaQuery();
			if(TsBqUtils.isNotNull(gasAnalyseRatioRing.getYearMonths())){
				analyseRatioWrapper.eq(GasAnalyseRatioWithEntity::getYearMonths,gasAnalyseRatioRing.getYearMonths());
			}
			
			analyseRatioWrapper.eq(GasAnalyseRatioWithEntity::getTaxorgcode,deptId);
			List<GasAnalyseRatioWithEntity> list = gasAnalyseRatioWithService.list(analyseRatioWrapper);
			
			if(TsBqUtils.isNotNull(list)){
				// 计算销售、同比销售、同比 等平均值
				// 销售值
				double averageSale = list.stream()
	                    .mapToDouble(GasAnalyseRatioWithEntity::getSaleAsDouble)
	                    .sum();
				
				// 比较销售值
				double averageUpSale = list.stream()
	                    .mapToDouble(GasAnalyseRatioWithEntity::getUpSaleAsDouble)
	                    .sum();
				
				String averageSaleStr = Double.toString(averageSale);
				String averageUpSaleStr = Double.toString(averageUpSale);
				String ratioRingSale = getRatioWith(averageUpSaleStr,averageSaleStr);
				
				// 销售笔数
				int averageSaleAmount = (int)list.stream()
	                    .mapToInt(GasAnalyseRatioWithEntity::getSaleAmountAsInt)
	                    .sum();
				
				// 比较销售笔数
				int averageUpSaleAmount = (int)list.stream()
	                    .mapToInt(GasAnalyseRatioWithEntity::getUpSaleAmountAsInt)
	                    .sum();
				
				String averageSaleAmountStr = averageSaleAmount + "";
				String averageUpSaleAmountStr = averageUpSaleAmount + "";
				String ratioRingSaleAmount = getRatioWith(averageUpSaleAmountStr,averageSaleAmountStr);
				
				BigDecimal averageSaleBd = new BigDecimal(averageSaleStr);
				BigDecimal averageUpSaleBd = new BigDecimal(averageUpSaleStr);
				
				dept.setAverageSale(String.valueOf(averageSaleBd.setScale(2, BigDecimal.ROUND_HALF_UP)));
				dept.setAverageUpSale(String.valueOf(averageUpSaleBd.setScale(2, BigDecimal.ROUND_HALF_UP)));
				
				dept.setRatioRingSale(ratioRingSale);
				
				dept.setAverageSaleAmount(averageSaleAmountStr);
				dept.setAverageUpSaleAsAmount(averageUpSaleAmountStr);
				dept.setRatioRingSaleAmount(ratioRingSaleAmount);
				
				dept.setYearMonths(yearMonths);
				
			}
			
			
		}
		
		return DataResult.success(iPage);
	}
	
	
    
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据（油站）")
	@PostMapping("/list2")
	@ResponseBody
	public DataResult list2(@RequestBody GasAnalyseRatioWithEntity gasAnalyseRatioWith) {

		String taxorgcode = gasAnalyseRatioWith.getTaxorgcode();
		String yearMonths = gasAnalyseRatioWith.getYearMonths();
		if (TsBqUtils.isNull(taxorgcode)) {
			return DataResult.fail("taxorgcode不能为空！");
		}

		if (TsBqUtils.isNull(yearMonths)) {
			return DataResult.fail("yearMonths不能为空！");
		}

		Page page = new Page(gasAnalyseRatioWith.getPage(), gasAnalyseRatioWith.getLimit());
		LambdaQueryWrapper<GasAnalyseRatioWithEntity> queryWrapper = Wrappers.lambdaQuery();

		queryWrapper.eq(GasAnalyseRatioWithEntity::getTaxorgcode, taxorgcode);

		queryWrapper.eq(GasAnalyseRatioWithEntity::getYearMonths, yearMonths);

		IPage<GasAnalyseRatioWithEntity> iPage = gasAnalyseRatioWithService.page(page, queryWrapper);
		return DataResult.success(iPage);
		
	}
	
	
    private static String getRatioWith(String upSale, String sale) {
		if (upSale.equals("0") || sale.equals("0")|| upSale.equals("0.0") ||sale.equals("0.0")) {
			return "0";
		}

		// 同比增长率计算公式为同比增长率=（本期数－同期数）/同期数×100%
		BigDecimal _upSale = new BigDecimal(upSale);
		BigDecimal _sale = new BigDecimal(sale);
		BigDecimal result = (_sale.subtract(_upSale)).divide(_upSale, 2, BigDecimal.ROUND_HALF_UP);
		return result.multiply(new BigDecimal(100)).toString() + "%";
	}

}
